/// 闭包中的例子
/// 实现一个缓存，只处理第一次传入的值并保存
///
struct CaCher<T>
where
    T: Fn(u32) -> u32
{
    calcuation: T,
    value: Option<u32>,
}

impl <T> CaCher<T>
where
    T: Fn(u32) -> u32
{
    fn new(calcuation: T) -> CaCher<T> {
        CaCher {
            calcuation,
            value: None,
        }
    }
    fn value(&mut self, arg: u32) -> u32 {
        match self.value {
            None => {
                let v = (self.calcuation)(arg);
                self.value = Some(v);
                v
            }
            Some(v) => v
        }
    }
}
fn main() {
    let mut c = CaCher::new(|x| x + 1);
    let v1 = c.value(1);
    println!("v1 = {}", v1);
    println!("v2 = {}", c.value(4));
    println!("v3 = {}", c.value(5));

    // 捕获环境中的变量
    let y = 4;
    let equal_to_x = |x| x == y;
    let x = 4;
    assert!(equal_to_x(x));
}
